package com.lemon.smartsafetynew.ui.activity.incident;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Button;
import android.widget.TextView;

import com.lemon.android.http.HttpUtils;
import com.lemon.android.http.LemonRequestParams;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppManager;
import com.lemon.smartsafety.app.AppService;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafetynew.ui.activity.base.SwipeBackActivity;
import com.lemon.smartsafety.utils.app.HUDUtil;
import com.lemon.smartsafety.utils.app.UIHelper;
import com.lemon.smartsafety.utils.common.LemonFileHelper;
import com.lemon.smartsafetynew.entity.common.DateTypeEnum;
import com.lemon.smartsafetynew.entity.event.common.ViewEvent;
import com.lemon.smartsafetynew.entity.incident.IncidentSafePatrolChildItemVo;
import com.lemon.smartsafetynew.entity.incident.IncidentVo;
import com.lemon.smartsafetynew.entity.event.incident.MediaEvent;
import com.lemon.smartsafetynew.entity.patrol.SafePatrolMediaVo;
import com.lemon.smartsafetynew.net.services.IncidentServices;
import com.lemon.smartsafetynew.ui.adapter.incident.IncidentSafePatrolCheckItemAdapter;
import com.lemon.smartsafetynew.util.common.CommonUtil;
import com.lemon.smartsafetynew.util.constants.KeyConstants;
import com.lemon.smartsafetynew.util.incident.IncidentUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import cn.finalteam.galleryfinal.model.PhotoInfo;

/**
 * Created by Andrew on 2017/9/6.
 */

public class IncidentSafePatrolProcessActivity extends SwipeBackActivity {

    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;
    @Bind(R.id.check_item_next_btn)
    Button checkItemNextBtn;

    @Bind(R.id.incident_source_tv)
    TextView incidentSourceTv;
    @Bind(R.id.incident_date_tv)
    TextView incidentDateTv;
    @Bind(R.id.incident_check_person_tv)
    TextView incidentCheckPersonTv;
    @Bind(R.id.incident_check_item_tv)
    TextView incidentCheckItemTv;
    @Bind(R.id.incident_check_item_position_tv)
    TextView incidentCheckItemPositionTv;

    private IncidentSafePatrolCheckItemAdapter mAdapter;
    private List<IncidentSafePatrolChildItemVo> mDataList = new ArrayList<>();

    private static IncidentVo mIncidentVo;
    private IncidentSafePatrolChildItemVo mIncidentSafePatrolChildItemVo;

    @Override
    protected void getBundleArgs() {
        super.getBundleArgs();

        Bundle bundle = getIntent().getExtras();

        if (bundle != null) {
            mIncidentVo = (IncidentVo) bundle.getSerializable(KeyConstants.KEY_INCIDENT_OBJ);
        } else {
            callFinish();
        }
    }

    @Override
    protected void initTitle() {
        this.setBarTitle("事件处理");
    }

    @Override
    protected void callFinish() {
        AppService.getBus().post(new ViewEvent(IncidentSafePatrolProcessActivity.class.getName()));
        AppManager.getAppManager().finishActivity(this);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_incident_safe_patrol_process;
    }

    @Override
    protected void initViews() {
        super.initViews();

        initRecyclerView();
        initCommonView();

        if (IncidentUtil.isDone(mIncidentVo.getStatus())) { //已处理，查看处理历史
            initDone();
        } else {                                            //未处理，做异场事件的处理
            initToDo();
        }

        // ======== 获取数据 =========
        getNetData();
    }


    /**
     * 初始化
     */
    private void initRecyclerView() {

        mAdapter = new IncidentSafePatrolCheckItemAdapter(mDataList);

        LinearLayoutManager layoutManager = new LinearLayoutManager(IncidentSafePatrolProcessActivity.this, LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setNestedScrollingEnabled(false);
        recyclerView.setAdapter(mAdapter);

    }

    private void initCommonView() {
        incidentSourceTv.setText(IncidentUtil.getIncidentSourceStrRes(mIncidentVo.getSource_type()));
        incidentDateTv.setText(CommonUtil.secondToTimeStr(mIncidentVo.getReport_time(), DateTypeEnum.DAY));
        incidentCheckPersonTv.setText(CommonUtil.avoidNullString(mIncidentVo.getReport_user_name()));
        incidentCheckItemTv.setText(CommonUtil.avoidNullString(mIncidentVo.getName()));
        incidentCheckItemPositionTv.setText(CommonUtil.avoidNullString(mIncidentVo.getLocation()));
    }

    /**
     * 事件已处理
     */
    private void initToDo() {
        checkItemNextBtn.setText("下一步");
    }

    /**
     * 事件未处理
     */
    private void initDone() {
        checkItemNextBtn.setText("处理历史");
    }

    /**
     * 获取事件详情数据
     */
    private void getNetData() {
        LemonRequestParams params = new LemonRequestParams("");
        params.put("event_id", mIncidentVo.getId());

        IncidentServices
                .init()
                .getIncidentDetail(params);
    }

    /**
     * 下一步 或 处理历史
     */
    @OnClick(R.id.check_item_next_btn)
    public void onViewClicked() {

        Bundle bundle = new Bundle();
        bundle.putSerializable(KeyConstants.KEY_INCIDENT_OBJ, mIncidentVo);
        bundle.putSerializable(KeyConstants.KEY_INCIDENT_CHILD_ITEM_OBJ, mIncidentSafePatrolChildItemVo);
        UIHelper.showActivity(IncidentSafePatrolProcessActivity.this, bundle, IncidentSafePatrolProcessTwoActivity.class);

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(HttpCallbackEvent event) {

        if (KeyConstants.URL_GET_INCIDENT_SAFE_PATROL_DETAIL.equals(event.getTag())) {

            if (HandlerCallback.HttpFlow.START == event.getHttpFlow()) {
                mHUDUtil.show();
            } else if (HandlerCallback.HttpFlow.FINISH == event.getHttpFlow()) {
                mHUDUtil.hidden();

                if (Constants.Result.SUCCESS == event.getEventResult()) {

                    if (event.getObj() instanceof IncidentSafePatrolChildItemVo) {
                        if (mAdapter != null) {
                            mDataList.clear();
                            mAdapter.notifyDataSetChanged();
                            mAdapter.addItem((IncidentSafePatrolChildItemVo) event.getObj());
                            mIncidentSafePatrolChildItemVo = (IncidentSafePatrolChildItemVo) event.getObj();
                        }
                    }

                } else if (Constants.Result.ERROR == event.getEventResult()) {
                    mHUDUtil.showErrorTip(event.getMsg(), new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {
                            callFinish();
                        }
                    });
                }
            }

        }

    }

    /**
     * 显示图片和音频详情
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMediaEvent(MediaEvent event) {

        if(IncidentSafePatrolProcessActivity.class.getName().equals(event.getTag())) {

            SafePatrolMediaVo data = event.getMediaVos().get(event.getPosition());

            if (LemonFileHelper.isImageUrl(data.getData_url())) {
                List<SafePatrolMediaVo> mediaVos = event.getMediaVos();
                List<PhotoInfo> photos = new ArrayList<>();

                int j = 0;
                int currentItem = 0;
                for (int i = 0; i < mediaVos.size(); i++) {
                    if (LemonFileHelper.isImageUrl(mediaVos.get(i).getData_url())) {

                        if (data.getData_url().equals(mediaVos.get(i).getData_url())) {
                            currentItem = j;
                        }

                        PhotoInfo photoInfo = new PhotoInfo();
                        photoInfo.setPhotoId(j);
                        photoInfo.setPhotoPath(HttpUtils.formatFilesUrl(mediaVos.get(i).getData_url()));
                        photos.add(photoInfo);
                        j++;
                    }
                }

                if (photos != null && photos.size() != 0) {
                    UIHelper.showPhotoView(this, photos, currentItem);
                }
            } else if (LemonFileHelper.isVoiceUrl(data.getData_url())) {
                playVoice(HttpUtils.formatFilesUrl(data.getData_url()));
            }

        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onFinishEvent(ViewEvent event) {
        if (IncidentSafePatrolProcessTwoActivity.class.getName().equals(event.getTag())) {
            callFinish();
        }
    }
}
